

import 'package:erp/Entity/CustomerType.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/AccountStore.dart';
import 'package:erp/Store/CustomerTypeStore.dart';
import 'package:erp/global.dart';

void registerCustomerTypeEvents(){
    globalBus.subscribe(Events.CUSTOMER_TYPE_SELECT_REQUEST, (bus, data) async {
      try {
        var result = await externalInterface.getCustomerTypes(AccountStore.signInResult.token);
        CustomerTypeStore.customerTypes = result;

        globalBus.publish(Events.CUSTOMER_TYPE_SELECT_SUCCESS, result);
      }
      catch (exception) {
        globalBus.publish(Events.CUSTOMER_TYPE_SELECT_ERROR, exception);
      }
    });

    globalBus.subscribe<CustomerType>(Events.CUSTOMER_TYPE_INSERT_REQUEST, (bus, data) async {
      try {
        var result = await externalInterface.addCustomerType(AccountStore.signInResult.token, data);
        CustomerTypeStore.customerTypes.add(result);
        globalBus.publish(Events.CUSTOMER_TYPE_INSERT_SUCCESS, result);
      }
      catch (exception){
        globalBus.publish(Events.CUSTOMER_TYPE_INSERT_ERROR, exception);
      }
    });

    globalBus.subscribe<CustomerType>(Events.CUSTOMER_TYPE_UPDATE_REQUEST, (bus, data) async {
      try {
        var result = await externalInterface.updateCustomerType(AccountStore.signInResult.token, data);
        var customerType = CustomerTypeStore.customerTypes.singleWhere((item) => item.id == result.id);
        customerType.name = result.name;
        customerType.memo = result.memo;
        customerType.createdAt = result.createdAt;
        customerType.isremove = result.isremove;
        customerType.updatedAt = result.updatedAt;
        customerType.shop = result.shop;

        globalBus.publish(Events.CUSTOMER_TYPE_UPDATE_SUCCESS, customerType);
      }
      catch (exception){
        globalBus.publish(Events.CUSTOMER_TYPE_UPDATE_ERROR, exception);
      }
    });

    globalBus.subscribe<CustomerType>(Events.CUSTOMER_TYPE_DELETE_REQUEST, (bus, data) async {
      try {
        var result = await externalInterface.deleteCustomerType(AccountStore.signInResult.token, data);
        CustomerTypeStore.customerTypes.removeWhere((item) => item.id == data.id);
        globalBus.publish(Events.CUSTOMER_TYPE_DELETE_SUCCESS, data);
      }
      catch (exception){
        globalBus.publish(Events.CUSTOMER_TYPE_DELETE_ERROR, exception);
      }
    });
}